from datetime import datetime
from sqlalchemy import Column, Integer, String, ForeignKey
from exception import JsonException
from model import db
from model.config import get_config
import requests
import uuid
import hashlib
from sqlalchemy.orm import relationship

# 定义映射类User，其继承上一步创建的Base
class User(db.Base):
    # 指定本类映射到users表
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String)
    sex = Column(String)
    avatar = Column(String)

    openid = Column(String)
    token = Column(String)
    access_token = Column(String)

    trueName = Column(String)
    mobile = Column(String)
    areaCode = Column(String)
    areaInfo = Column(String)
    address = Column(String)
    company = Column(String)

    true_question_count = Column(Integer)

    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict


# 用户提交记录
class UserCommit(db.Base):
    # 指定本类映射到表
    __tablename__ = 'user_commit'

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer)

    created_time = Column(String,server_default="CURRENT_TIMESTAMP")
    updated_time = Column(String,server_default="CURRENT_TIMESTAMP")

    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict
    

# 定义映射类User，其继承上一步创建的Base
class UserQuestion(db.Base):
    # 指定本类映射到表
    __tablename__ = 'user_question'

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_commit_id = Column(Integer)
    question_id = Column(Integer)
    user_id = Column(Integer)
    is_true = Column(String)


    type = Column(String)
    content = Column(String)
    order = Column(Integer)

    created_time = Column(String,server_default="CURRENT_TIMESTAMP")
    updated_time = Column(String,server_default="CURRENT_TIMESTAMP")

    options = relationship("UserQuestionOption",order_by="asc(UserQuestionOption.order)")
    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict


class UserQuestionOption(db.Base):
    # 指定本类映射到表
    __tablename__ = 'user_question_option'

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer)
    selected = Column(String)
    user_question_id = Column(Integer,ForeignKey('user_question.id'))

    ind = Column(String)
    content = Column(String)
    is_true = Column(String)
    order = Column(Integer)

    created_time = Column(String,server_default="CURRENT_TIMESTAMP")
    updated_time = Column(String,server_default="CURRENT_TIMESTAMP")

    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict


## 用户注册获取 获取openid
def regist(code:str):
    code = code[:200]

    # 配置文件
    conf = get_config()
    if not conf:
        raise JsonException("非法请求：配置信息错误")
    
    appid = conf.gzh_appid
    secret = conf.gzh_secret
    
    url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code"

    response = requests.get(url)
    if response.status_code != 200:
        # 打印响应内容
        raise JsonException(f"发生错误,获取openid失败：{response.text}")

    data = response.json()
    if "openid" not in data:
        raise JsonException(f"发生错误,获取openid失败：{data}")
    

    # openid
    openid = data["openid"]
    # access_token
    access_token = data["access_token"]

    ## 获取用户信息接口
    url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"
    response = requests.get(url)

    if response.status_code != 200:
        # 打印响应内容
        raise JsonException(f"发生错误,获取微信信息失败：{response.text}")
    

    data = response.json()
    if data.get("errcode",0) != 0:
        errcode = data["errcode"]
        raise JsonException(f"发生错误,获取微信信息失败：{errcode}")

    sex = ''
    if data['sex'] == 1:
        sex = "男"
    elif data['sex'] == 2:
        sex = "女"

    data['nickname'] = data['nickname'].encode('iso-8859-1').decode('utf-8')

    one = None
    uuid4 = uuid.uuid4()
    uuid_str = str(uuid4)
    token = openid + uuid_str

    # md5加密
    token_md5 = hashlib.md5(token.encode('utf-8')).hexdigest()

    # 查询是否存在用户
    with db.Session() as session:
        one = session.query(User).filter(
            User.openid == openid
        ).first()

        if one == None:
            # 新增用户
            one = User()
            one.openid = openid
            one.access_token = access_token
            one.name = data['nickname']
            one.sex = sex
            one.avatar = data['headimgurl']
            one.token = token_md5
            one.true_question_count = 0

            session.add(one)
            session.commit()
        else:
            session.query(User).filter(
                User.openid == openid
            ).update({"access_token":access_token,"name":data['nickname'],"sex":sex,"avatar":data['headimgurl'],"token":token_md5})
            session.commit()

        # 重新获取用户信息
        one = session.query(User).filter(
            User.openid == openid
        ).first()

    return one


